package source.model;

import java.util.*;
/**
 * PositionMap class is responsible for associating GameObjects with a Position.
 * The class uses a HashTable to get a Position for a supplied ObjectID.  The
 * array of IdLists allows for an array of ObjectID's to be returned for a given
 * position.
 * @author Sean Larson
 *
 */
public class PositionMap {

	private Hashtable<String, Position> lib;
	private IdList[][] grid;
	
	public PositionMap() {
		grid = new IdList[Position.xBound+1][Position.yBound+1];
		for ( int i = 0; i <= Position.xBound; i++) 
			for ( int j = 0; j <= Position.yBound; j++) {
				grid[i][j] = new IdList();
			}
		
		lib = new Hashtable<String, Position>();
	}
		
	public boolean addGameObject( GameObject go, Position pos ) {
		lib.put(go.objectID().getID(), pos);
		return grid[pos.getX()][pos.getY()].add(go.objectID());
	}
	
	public boolean addGameObject( GameObject go, int x, int y ) {
		Position pos = new Position( x, y );
		return addGameObject( go, pos );
	}
	
	public boolean removeObject( ObjectID id ) {
		Position pos = lib.remove(id.getID());
		return grid[pos.getX()][pos.getY()].remove(id);
	}
	
	public boolean removeObject( GameObject go ) {
		return removeObject( go.objectID() );
	}
	
	public Position getPosition( ObjectID id ) {
		return lib.get(id.getID());
	}
	
	public Position getPosition( GameObject go ) {
		return getPosition( go.objectID() );
	}
	
	public boolean changePosition( ObjectID id, Position newPos ) {
		Position old = lib.get(id.getID());
		if (old.equals(null))	return false;
		grid[old.getX()][old.getY()].remove(id);
		lib.put(id.getID(), newPos);
		return grid[newPos.getX()][newPos.getY()].add(id);
	}
	
	public ObjectID[] getAt( Position p ) {
		return grid[p.getX()][p.getY()].getIds();
	}
	
	public ObjectID[] getAt( int x, int y ) {
		return getAt( new Position( x, y ) );
	}
}
